package cn.gson.school.Interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LoginInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 调用session
		HttpSession session = request.getSession();
		// 判断用户是否登录
		if (session.getAttribute("user") == null) {// 如果读取到的session用户是空的
			// 判断是否是ajax请求，
			// 如果格式是X-Requested-With：XMLHttpRequest就不会因为session失效而直接跳入登入界面
			if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) {
				// 如果是ajax请求，则设置一个请求状态，
				response.sendError(401);
			} else {
				// 否则，进入这里调用这里的代码段
				// 未登录，跳转到登录页面进行登录
				response.sendRedirect(request.getContextPath() + "/login");
			}
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}
}
